#!coding=utf-8
import threading
from print_s import print_safe as print
import time
import random

# 创建一个包含三个线程的屏障
barrier = threading.Barrier(3)

# 线程函数
def worker():
    print(f"Worker {threading.current_thread().name} is waiting at the barrier.")
    time.sleep(random.randint(1, 5))
    barrier.wait()
    print(f"Worker {threading.current_thread().name} is proceeding after the barrier.")

# 创建并启动线程
threads = []
for i in range(3):
    thread = threading.Thread(target=worker)
    threads.append(thread)
    thread.start()

# 等待线程完成
for thread in threads:
    thread.join()

# # 重置屏障，允许新的线程加入
barrier.reset()
# 如果不调用 reset() 方法，当所有等待的线程达到线程障碍数量（parties）后，Barrier 会按照正常的流程执行相应的操作，然后可以继续被使用。

# 再次创建并启动线程， 并发修改为2
for i in range(2):
    thread = threading.Thread(target=worker)
    threads.append(thread)
    thread.start()

# 等待线程完成
for thread in threads:
    thread.join()

print("All workers have passed the barrier.")
